from fastapi.requests import Request
from models import AsyncSessionFactory


async def create_session_middleware(request: Request, call_next):
    # 1 请求到视图前
    session = AsyncSessionFactory()
    request.state.session = session
    # 等价下面这一行
    # setattr(request.state, 'session', session)

    response = await call_next(request)

    # 2 响应返回浏览器之前
    await session.close()
    return response
